package Controller.DVNet;

import java.util.HashMap;
import java.util.Map;

public class NetworkSetting {
    public Map<String, Router> routerMap;
    public Map<String, Area> areaMap;
    public Area defaultArea;

    public NetworkSetting(){
        routerMap = new HashMap<>();
        areaMap = new HashMap<>();
        defaultArea = null;
    }

    public void setArea(String areaName, String ... routerName){
        Area area = areaMap.get(areaName);
        if(area == null){
            area = new Area(areaName);
            areaMap.put(areaName, area);
        }
        addAreaRouter(area, routerName);
        if(defaultArea == null){
            defaultArea = area;
            Router.defaultArea = area;
        }
    }

    public void addAreaRouter(Area area, String ... names){
        for(String name: names){
            Router r;
            if(!routerMap.containsKey(name)){
                r = new Router(name, area);
                routerMap.put(name, r);
            }else{
                r = routerMap.get(name);
                r.area = area;
            }
            area.routers.put(name, r);
        }
    }

    public Router getRouter(String name){
        return routerMap.getOrDefault(name, null);
    }

    public void addTopology(String router1, String router1Port, String router2, String router2Port){
        Router r1 = getRouter(router1), r2 = getRouter(router2);
        RouterPort p1 = r1.getRouterPort(router1Port);
        RouterPort p2 = r2.getRouterPort(router2Port);
        addLink(p1, p2);
    }

    public void addLink(RouterPort p1, RouterPort p2){
        Router r1 = p1.router;
        Router r2 = p2.router;

        if(r1.area != r2.area){
            r1.isBorder = true;
            r2.isBorder = true;
            p1.linkPort = p2;
            p2.linkPort = p1;
            r1.area.borderRouters.add(r1);
            r1.area.borderRouterPorts.add(p1);
            r1.borderPorts.add(p1);
            r2.area.borderRouters.add(r2);
            r2.area.borderRouterPorts.add(p2);
            r2.borderPorts.add(p2);
        }
    }
}

